package com.lottery.service.qiuqiu.lobbyService;

import com.lottery.dao.qiuqiu.lobbyDao.BettinginfoDao;
import com.lottery.dao.qiuqiu.lobbyDao.LotteryDao;
import com.lottery.dao.qiuqiu.wealthDao.AccountDao;
import com.lottery.dto.ResultDto;
import com.lottery.entity.Account;
import com.lottery.entity.Bettinginfo;
import com.lottery.entity.Lottery;
import com.lottery.entity.LotteryExchange;
import com.lottery.initData.InitData;
import com.lottery.service.qiuqiu.JedisClient;
import com.lottery.service.qiuqiu.statisticsService.AgencyMoneyService;
import com.lottery.service.qiuqiu.statisticsService.PlaywayMoneyService;
import com.lottery.service.qiuqiu.statisticsService.TotalMoneyService;
import com.lottery.utils.DealWithDouble;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class LotteryDrawService {

    @Autowired
    private BettinginfoDao bettinginfoDao;

    @Autowired
    private LotteryExchangeService lotteryExchangeService;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AgencyMoneyService agencyMoneyService;

    @Autowired
    private PlaywayMoneyService playwayMoneyService;

    @Autowired
    private TotalMoneyService totalMoneyService;

    @Autowired
    private JedisClient jedisClient;

    @Resource
    private LotteryDao lotteryDao;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 中奖信息标志key
    @Value("${PC28FLG}")
    private String PC28FLG;
    @Value("${SSCFLG}")
    private String SSCFLG;
    @Value("${BJSCFLG}")
    private String BJSCFLG;
    // 开始下注
    @Value("${BEGAINBET}")
    private String BEGAINBET;
    // 开始下注
    @Value("${OPENNUM}")
    private String OPENNUM;
    // 开奖信息前缀
    @Value("${BEFOR}")
    private String BEFOR;
    // 开奖信息后缀
    @Value("${AFTER}")
    private String AFTER;

    public static boolean sscbl = true;
    public static boolean bjscbl = true;


    /**
     * 分割汉字和数字
     */
    private static String Division(String s) {

        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]+|\\d+");
        Matcher m = p.matcher(s);
        String group = "";
        if (m.find()) {
            group = m.group();
        }
        return group;
    }

    /**
     * 统计字符串中包含字符的个数
     *
     * @param str
     * @param s
     * @return
     */
    private static int Count(String[] str, String s) {

        int count = 0;
        for (int index = 0; index < str.length; index++) {

            if (str[index].equals(s)) {

                count++;
            }
        }

        return count;
    }

    /**
     * 判断数字组合玩法
     *
     * @param opencode
     * @param s
     * @return
     */
    private static boolean Include(String opencode, String s) {
        boolean flg = false;
        for (int index = 0; index < s.length(); index++) {
            if (opencode.indexOf(s.charAt(index)) != -1) {
                flg = true;
            } else {
                return false;
            }
        }

        return flg;
    }

    private static int IncludeNums(String opencode, String s) {
        // boolean flg = false;
        int num = 0;
        String tmpStr = opencode;
        int length = 0;
        for (int index = 0; index < s.length(); index++) {
            length = tmpStr.length();
            tmpStr = tmpStr.replaceAll(s.substring(index, index + 1), "");
            int changeLength = length - tmpStr.length();
            if (changeLength > 0) {
                num += changeLength;
            } else {
                return 0;
            }
        }

        return num;
    }

    /**
     * ssc开奖规则
     *
     * @param opencode
     * @param expect
     * @param lotteyType
     * @return
     */

    public void sscYesWinningFactory(String opencode, String expect, int lotteyType) {
        // 中奖状态
        sscbl = false;

        jedisClient.del(SSCFLG);

        ResultDto<LotteryExchange> result = new ResultDto<LotteryExchange>();

        if (null == opencode || "".equals(opencode.trim())) {
            sscbl = true;
            logger.debug("ssc  开奖结果不能为空！");
        }

        // 分割字符串
        String[] str = opencode.split(",");

        if (str.length != 5) {
            sscbl = true;
            logger.error("ssc 开奖结果格式不正确！");
        }
        // 五个数字总和
        int amount = Integer.parseInt(str[0]) + Integer.parseInt(str[1]) + Integer.parseInt(str[2])
                + Integer.parseInt(str[3]) + Integer.parseInt(str[4]);

        int pageNow = 1;
        // 下注来源(0:代表注册用户,1:代表游客或代表机器人)
        int betResource = 0;


        while (true) {
            List<Bettinginfo> bettinginfoList = bettinginfoDao.selectBettinginfoPage(expect, lotteyType);
            logger.info("ssc 查询下注记录的数据  dataTag={}", bettinginfoList);

            // 判断下注表是否有数据
            if (null == bettinginfoList || bettinginfoList.size() == 0) {
                sscbl = true;
                break;
            }

            // 正常用户遍历
            //double accountMoney = bettinginfoList.get(0).getAccountMoney();
            for (int i = 0; i < bettinginfoList.size(); i++) {
                Bettinginfo bettinginfo = bettinginfoList.get(i);
                try {
                    // 玩法名称id
                    int playwayinfoId = bettinginfo.getPlaywayinfoId();
                    List<String> ruleList = InitData.SSC_WINRESULT_MAP.get(playwayinfoId);
                    String betting = bettinginfo.getBettingrule();
                    boolean sign = true;
                    //
                    if (playwayinfoId == 7) {
                        for (String ss : ruleList) {
                            String zz = betting.substring(3);
                            String judge = ss.substring(0, 1);
                            if (zz.equals(judge)) {
                                lotteryExchangeService.insertLotteryExchange(bettinginfo, ss, lotteyType);
                                //accountMoney = (double) aa.getData2();
                                sign = false;
                            }
                        }
                    } else {
                        if (ruleList.contains(betting)) {
                            lotteryExchangeService.insertLotteryExchange(bettinginfo, betting, lotteyType);
                            //accountMoney = (double) aa.getData2();
                            sign = false;
                        }
                    }

                    if (sign) {
                        bettinginfo.setState(0);
                        bettinginfo.setAccountChange(bettinginfo.getAccountChange());
//                        if (i == 0) {
//                            Account account = accountDao.selectAccountByUserId(bettinginfo.getUserId());
//                            bettinginfoList.get(i).setAccountMoney(account.getAccountFunds());
//                            bettinginfo.setAccountMoney(account.getAccountFunds());
//                        } else {
//                            bettinginfo.setAccountMoney(DealWithDouble.sum(bettinginfoList.get(i - 1).getAccountMoney(), bettinginfo.getAccountChange(), 2, 4));
//                            bettinginfoList.get(i).setAccountMoney(bettinginfo.getAccountMoney());
//                        }
//                        if (i == 0) {
//                            accountMoney = accountMoney;
//                        } else {
//                            accountMoney = DealWithDouble.sum(accountMoney, bettinginfo.getAccountChange(), 2, 4);
//                        }
//                        bettinginfo.setAccountMoney(accountMoney);
                        Account account = accountDao.selectAccountByUserId(bettinginfo.getUserId());
                        bettinginfo.setAccountMoney(account.getAccountFunds());
                        bettinginfo.setRemark("期号[" + bettinginfo.getExpect() + "]竞猜[" + bettinginfo.getBettingrule() + "/" + bettinginfo.getBettingmoney() + "]");
                        bettinginfoDao.updateBettinginfo(bettinginfo);
                    }
                } catch (Exception e) {
                    logger.error("ssc kaijiang error:", e);
                }
                pageNow++;
            }

            // 游客开奖
//        for (Entry<Integer, ArrayList<Bettinginfo>> entity : TouristData.touristBetting.entrySet()) {
//            // 将下注来源改为游客
//            betResource = 1;
//            ArrayList<Bettinginfo> bets = entity.getValue();
//            try {
//                ArrayList<LotteryExchange> lotteryExchangelist = new ArrayList<LotteryExchange>();
//                for (Bettinginfo bettinginfo : bets) {
//                    // 玩法名称
//                    String playwayName = bettinginfo.getPlaywayName();
//                    SscYesWinningImpl sscYesWinning = new SscFactory().getSscYesWinning(playwayName);
//                    boolean sign = sscYesWinning.winning(bettinginfo, lotteyType, amount, opencode, betResource,
//                            lotteryExchangelist, sscPlayUtilsNoNum, sscPlayUtilNum);
//                    if (sign) {
//                        LotteryExchange lotteryExchange = new LotteryExchange();
//                        lotteryExchange.setUserId(bettinginfo.getUserId());
//                        lotteryExchange.setBettinginfoId(bettinginfo.getBettingnumber());
//                        lotteryExchange.setBettingrule(bettinginfo.getBettingrule());
//                        lotteryExchange.setPlaywayName(bettinginfo.getPlaywayName());
//                        lotteryExchange.setExpect(bettinginfo.getExpect());
//                        lotteryExchange.setWinningamount(0);
//                        lotteryExchangelist.add(lotteryExchange);
//                    }
//                }
//                TouristData.touristWin.put(entity.getKey(), lotteryExchangelist);
//                TouristData.touristBetting.get(entity.getKey()).clear();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

            // 遍历机器人开奖
//        logger.debug("****sscrobot start winbet  in  ***************");
//        for (Entry<Integer, ArrayList<Bettinginfo>> entry : RobotParams.robotSscBetting.entrySet()) {
//            ArrayList<Bettinginfo> bets = entry.getValue();
//            ArrayList<LotteryExchange> lotteryExchangelist = new ArrayList<LotteryExchange>();
//            try {
//                for (Bettinginfo bettinginfo : bets) {
//                    // 玩法名称
//                    String playwayName = bettinginfo.getPlaywayName();
//
//                    SscYesWinningImpl sscYesWinning = new SscFactory().getSscYesWinning(playwayName);
//
//                    boolean sign = false;
//                    betResource = 1;
//                    sign = sscYesWinning.winning(bettinginfo, lotteyType, amount, opencode, betResource,
//                            lotteryExchangelist, sscPlayUtilsNoNum, sscPlayUtilNum);
//                    if (sign) {
//                        LotteryExchange lotteryExchange = new LotteryExchange();
//                        lotteryExchange.setUserId(bettinginfo.getUserId());
//                        lotteryExchange.setBettinginfoId(bettinginfo.getBettingnumber());
//                        lotteryExchange.setBettingrule(bettinginfo.getBettingrule());
//                        lotteryExchange.setPlaywayName(bettinginfo.getPlaywayName());
//                        lotteryExchange.setExpect(bettinginfo.getExpect());
//                        lotteryExchange.setWinningamount(0);
//                        lotteryExchangelist.add(lotteryExchange);
//                    }
//                }
//
//                RobotParams.robotSscWin.put(entry.getKey(), lotteryExchangelist);
//                RobotParams.robotSscBetting.get(entry.getKey()).clear();
//            } catch (Exception e) {
//                logger.error("robot kaijiang error", e);
//                e.printStackTrace();
//            }
//        }


            try {
                // 用户比例分成
                //lotteryExchangeService.UserRateSharing(expect, lotteyType);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            logger.info("用户比例分成 yonghufc={}", "用户比例分成完成");


            // 开奖完成的状态
            sscbl = true;

            // 统计userTop10
            // userTop10Service.insetUserTop10(expect, lotteyType);
            // 每期代理商分类统计金额
            agencyMoneyService.insetAgencyMoney(expect);
            // 每期玩法分类统计金额
            playwayMoneyService.insetPlaywayMoney(expect);
            // 统计每期总金额
            totalMoneyService.insetTotalMoney(expect);
        }


    }

    // 将当前开奖信息插入数据库
    public Boolean insertLottery(String expect, int expectNum, String opencode, Date opentime, Integer lotteyType) {
        Lottery lottery = new Lottery();
        lottery.setExpect(expect);
        lottery.setExpectNum(expectNum);
        lottery.setOpencode(opencode);
        lottery.setOpentime(opentime);
        lottery.setInserttime(new Date());
        lottery.setLotteyType(lotteyType);
        logger.info("插入数据库:{}", lottery);
        try {
            lotteryDao.insertLottery(lottery);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //北京赛车开奖
    public void bjscYesWinningFactory(String opencode, String expect, int lotteyType) {
        // 中奖状态
        bjscbl = false;

        jedisClient.del(BJSCFLG);

        if (null == opencode || "".equals(opencode.trim())) {
            sscbl = true;
            logger.debug("bjsc  开奖结果不能为空！");
        }

        // 分割字符串
        String[] str = opencode.split(",");

        if (str.length != 10) {
            sscbl = true;
            logger.error("ssc 开奖结果格式不正确！");
        }

        int pageNow = 1;
        // 下注来源(0:代表注册用户,1:代表游客或代表机器人)
        int betResource = 0;


        while (true) {
            List<Bettinginfo> bettinginfoList = bettinginfoDao.selectBettinginfoPage(expect, lotteyType);
            logger.info("ssc 查询下注记录的数据  dataTag={}", bettinginfoList);

            // 判断下注表是否有数据
            if (null == bettinginfoList || bettinginfoList.size() == 0) {
                bjscbl = true;
                break;
            }

            // 正常用户遍历
            //double accountMoney = bettinginfoList.get(0).getAccountMoney();
            for (int i = 0; i < bettinginfoList.size(); i++) {
                Bettinginfo bettinginfo = bettinginfoList.get(i);
                try {
                    // 玩法名称id
                    int playwayinfoId = bettinginfo.getPlaywayinfoId();
                    List<String> ruleList = InitData.BJSC_WINRESULT_MAP.get(playwayinfoId);
                    String betting = bettinginfo.getBettingrule();
                    boolean sign = true;
                    //
                    if (playwayinfoId == 14) {
                        if (ruleList.contains(betting)) {
                            String ss = "冠亚";
                            lotteryExchangeService.insertLotteryExchange(bettinginfo, ss, lotteyType);
                            //accountMoney = (double)result.getData2();
                            sign = false;
                        }
                    } else {
                        if (ruleList.contains(betting)) {
                            lotteryExchangeService.insertLotteryExchange(bettinginfo, betting, lotteyType);
                            //accountMoney = (double)result.getData2();
                            sign = false;
                        }
                    }
                    if (sign) {
                        bettinginfo.setState(0);
                        bettinginfo.setAccountChange(bettinginfo.getAccountChange());
//                        if (i == 0) {
//                            Account account = accountDao.selectAccountByUserId(bettinginfo.getUserId());
//                            bettinginfoList.get(i).setAccountMoney(account.getAccountFunds());
//                            bettinginfo.setAccountMoney(account.getAccountFunds());
//                        } else {
//                            bettinginfo.setAccountMoney(DealWithDouble.sum(bettinginfoList.get(i - 1).getAccountMoney(), bettinginfo.getAccountChange(), 2, 4));
//                            bettinginfoList.get(i).setAccountMoney(bettinginfo.getAccountMoney());
//                        }
//                        if(i==0){
//                            accountMoney = accountMoney;
//                        }else{
//                            accountMoney = DealWithDouble.sum(accountMoney,bettinginfo.getAccountChange(),2,4);
//                        }

                        Account account = accountDao.selectAccountByUserId(bettinginfo.getUserId());
                        bettinginfo.setAccountMoney(account.getAccountFunds());
                        bettinginfo.setRemark("期号[" + bettinginfo.getExpect() + "]竞猜[" + bettinginfo.getBettingrule() + "/" + bettinginfo.getBettingmoney() + "]");
                        bettinginfoDao.updateBettinginfo(bettinginfo);
                    }
                } catch (Exception e) {
                    logger.error("bjsc kaijiang error:", e);
                }
                pageNow++;
            }

            // 游客开奖
//        for (Entry<Integer, ArrayList<Bettinginfo>> entity : TouristData.touristBetting.entrySet()) {
//            // 将下注来源改为游客
//            betResource = 1;
//            ArrayList<Bettinginfo> bets = entity.getValue();
//            try {
//                ArrayList<LotteryExchange> lotteryExchangelist = new ArrayList<LotteryExchange>();
//                for (Bettinginfo bettinginfo : bets) {
//                    // 玩法名称
//                    String playwayName = bettinginfo.getPlaywayName();
//                    SscYesWinningImpl sscYesWinning = new SscFactory().getSscYesWinning(playwayName);
//                    boolean sign = sscYesWinning.winning(bettinginfo, lotteyType, amount, opencode, betResource,
//                            lotteryExchangelist, sscPlayUtilsNoNum, sscPlayUtilNum);
//                    if (sign) {
//                        LotteryExchange lotteryExchange = new LotteryExchange();
//                        lotteryExchange.setUserId(bettinginfo.getUserId());
//                        lotteryExchange.setBettinginfoId(bettinginfo.getBettingnumber());
//                        lotteryExchange.setBettingrule(bettinginfo.getBettingrule());
//                        lotteryExchange.setPlaywayName(bettinginfo.getPlaywayName());
//                        lotteryExchange.setExpect(bettinginfo.getExpect());
//                        lotteryExchange.setWinningamount(0);
//                        lotteryExchangelist.add(lotteryExchange);
//                    }
//                }
//                TouristData.touristWin.put(entity.getKey(), lotteryExchangelist);
//                TouristData.touristBetting.get(entity.getKey()).clear();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

            // 遍历机器人开奖
//        logger.debug("****sscrobot start winbet  in  ***************");
//        for (Entry<Integer, ArrayList<Bettinginfo>> entry : RobotParams.robotSscBetting.entrySet()) {
//            ArrayList<Bettinginfo> bets = entry.getValue();
//            ArrayList<LotteryExchange> lotteryExchangelist = new ArrayList<LotteryExchange>();
//            try {
//                for (Bettinginfo bettinginfo : bets) {
//                    // 玩法名称
//                    String playwayName = bettinginfo.getPlaywayName();
//
//                    SscYesWinningImpl sscYesWinning = new SscFactory().getSscYesWinning(playwayName);
//
//                    boolean sign = false;
//                    betResource = 1;
//                    sign = sscYesWinning.winning(bettinginfo, lotteyType, amount, opencode, betResource,
//                            lotteryExchangelist, sscPlayUtilsNoNum, sscPlayUtilNum);
//                    if (sign) {
//                        LotteryExchange lotteryExchange = new LotteryExchange();
//                        lotteryExchange.setUserId(bettinginfo.getUserId());
//                        lotteryExchange.setBettinginfoId(bettinginfo.getBettingnumber());
//                        lotteryExchange.setBettingrule(bettinginfo.getBettingrule());
//                        lotteryExchange.setPlaywayName(bettinginfo.getPlaywayName());
//                        lotteryExchange.setExpect(bettinginfo.getExpect());
//                        lotteryExchange.setWinningamount(0);
//                        lotteryExchangelist.add(lotteryExchange);
//                    }
//                }
//
//                RobotParams.robotSscWin.put(entry.getKey(), lotteryExchangelist);
//                RobotParams.robotSscBetting.get(entry.getKey()).clear();
//            } catch (Exception e) {
//                logger.error("robot kaijiang error", e);
//                e.printStackTrace();
//            }
//        }


            try {
                // 用户比例分成
                //lotteryExchangeService.UserRateSharing(expect, lotteyType);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            logger.info("用户比例分成 yonghufc={}", "用户比例分成完成");


            // 开奖完成的状态
            sscbl = true;

            // 统计userTop10
            // userTop10Service.insetUserTop10(expect, lotteyType);
            // 每期代理商分类统计金额
            agencyMoneyService.insetAgencyMoney(expect);
            // 每期玩法分类统计金额
            playwayMoneyService.insetPlaywayMoney(expect);
            // 统计每期总金额
            totalMoneyService.insetTotalMoney(expect);
        }


    }
}